package com.winit.schedule.job.tracker.web.context;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.ContextLoaderListener;

import com.winit.schedule.job.tracker.conf.JobConfiguration;

public class SpringContextLoaderListener extends ContextLoaderListener {

    private static final Logger logger = LoggerFactory.getLogger(SpringContextLoaderListener.class);

    @Override
    protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
        Properties prop;

        String profiles = sc.getInitParameter("spring.profiles.default");

        String configFile = JobConfiguration.DEFAULT_CONFIG_FILENAME;

        int index = configFile.lastIndexOf(".");

        // 非生产环境，添加环境参数至配置文件名
        if (!"prod".equals(profiles)) {
            configFile = configFile.substring(0, index) + "." + profiles + configFile.substring(index);
        }

        // 设置配置文件至上下文中
        System.setProperty(JobConfiguration.CONFIG_FILE, configFile);

        logger.info("config filename : " + configFile);

        try {
            prop = PropertiesLoaderUtils.loadProperties(new ClassPathResource(configFile));

            //logger.info("use db.type is : " + prop.get(JobConfiguration.DB_TYPE).toString());

            // 在spring容器加载前初始化数据库类型
            //sc.setInitParameter(JobConfiguration.DB_TYPE, prop.get(JobConfiguration.DB_TYPE).toString());
        } catch (IOException e) {
            logger.error("Load config file failure, filename is : " + configFile, e);
        }
        super.customizeContext(sc, wac);
    }
}
